/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.qiujuer.genius.blur.utils;

import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.PixelMapHolder;
import ohos.agp.render.Texture;
import ohos.agp.utils.Matrix;
import ohos.agp.utils.RectFloat;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.media.image.ImagePacker;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.AlphaType;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.ScaleMode;
import ohos.media.image.common.Size;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class PixelMapUtils {

    /**
     * 对PixelMap进行压缩处理
     *
     * @param pixelMap          The PixelMap we are compress
     * @param compressFormat    The format of the compressed image
     * @param quality           Hint to the compressor, 0-100.
     * @param outputStream      The outputstream to write the compressed data.
     * @return                  true if successfully compressed to the specified stream.
     */
    public static boolean compress(PixelMap pixelMap,
                                   String compressFormat,
                                   int quality,
                                   OutputStream outputStream) {
        if (pixelMap == null) {
            return false;
        }
        ImagePacker imagePacker = ImagePacker.create();
        ImagePacker.PackingOptions packingOptions = new ImagePacker.PackingOptions();
        packingOptions.format = compressFormat;
        packingOptions.quality = quality;
        boolean result = imagePacker.initializePacking(outputStream, packingOptions);
        if (result) {
            imagePacker.addImage(pixelMap);
            imagePacker.finalizePacking();
            return true;
        } else {
            return false;
        }
    }

    public static PixelMap createBitmap(int width, int height, PixelFormat pixelFormat) {
        PixelMap.InitializationOptions initializationOptions = new PixelMap.InitializationOptions();
        initializationOptions.size = new Size(width, height);
        initializationOptions.pixelFormat = pixelFormat;
        initializationOptions.editable = true;
        return PixelMap.create(initializationOptions);
    }

    /**
     * 对PixelMap进行Matrix处理
     *
     * @param source    The PixelMap we are subsetting
     * @param x         The x coordinate of the first pixel in source
     * @param y         The y coordinate of the first pixel in source
     * @param width     The number of pixels in each row
     * @param height    The number of rows
     * @param matrix    Optional matrix to be applied to the pixels
     * @param filter    true if the source should be filtered.
     *                    Only applies if the matrix contains more than just
     *                    translation.
     * @return          A PixelMap that represents the specified subset of source
     */
    public static PixelMap createBitmap(PixelMap source, int x, int y, int width, int height,
                                          Matrix matrix, boolean filter){
        PixelMap.InitializationOptions initializationOptions = new PixelMap.InitializationOptions();

        RectFloat srcR = new RectFloat(x, y, x + width, y + height);
        RectFloat dstR = new RectFloat(0, 0, width, height);
        RectFloat deviceR = new RectFloat();

        PixelFormat newConfig = PixelFormat.ARGB_8888;
        final PixelFormat config = source.getImageInfo().pixelFormat;
        if (config != null) {
            if (config == PixelFormat.RGB_565) {
                newConfig = PixelFormat.RGB_565;
            } else {
                newConfig = PixelFormat.ARGB_8888;
            }
        }

        Paint paint = new Paint();
        paint.setFilterBitmap(filter);
        paint.setAntiAlias(true);
        if (matrix != null) {
            final boolean transformed = !matrix.rectStaysRect();
            if (transformed) {
                paint.setAntiAlias(true);
            }
            matrix.mapRect(deviceR, dstR);
        } else {
            deviceR = dstR;
        }

        int neww = Math.round(deviceR.getWidth());
        int newh = Math.round(deviceR.getHeight());
        initializationOptions.pixelFormat = newConfig;
        initializationOptions.size = new Size(neww, newh);
        initializationOptions.scaleMode = ScaleMode.CENTER_CROP;
        initializationOptions.alphaType = AlphaType.OPAQUE;
        PixelMap srcPixelMap = PixelMap.create(initializationOptions);
        Texture texture = new Texture(srcPixelMap);
        Canvas canvas = new Canvas(texture);

        canvas.translate(-deviceR.left, -deviceR.top);
        canvas.concat(matrix);
        canvas.drawPixelMapHolderRect(new PixelMapHolder(source), srcR, dstR, paint);
        return texture.getPixelMap();
    }

    public static PixelMap createBitmap(PixelMap source) {
        int width = source.getImageInfo().size.width;
        int height = source.getImageInfo().size.height;
        return createBitmap(source, 0, 0, width, height, null, false);
    }

    public static PixelMap createBitmap(PixelMap source, int x, int y, int width, int height){

        return createBitmap(source, 0, 0, width, height, null, false);
    }

    public static PixelMap getPixelMapFromResource(Context context, int resourceId) {
        InputStream inputStream = null;
        try {

            // 创建图像数据源ImageSource对象
            inputStream = context.getResourceManager().getResource(resourceId);
            ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions();
            srcOpts.formatHint = "image/jpg";
            ImageSource imageSource = ImageSource.create(inputStream, srcOpts);
            // 设置图片参数
            ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
            return imageSource.createPixelmap(decodingOptions);
        } catch (IOException e) {
//            HiLogUtil.showLog("ImageUtils", "IOException");
        } catch (NotExistException e) {
//            HiLogUtil.showLog("ImageUtils", "NotExistException");
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
//                    HiLogUtil.showLog("ImageUtils", "inputStream IOException");
                }
            }
        }
        return null;
    }
}
